<template>
  <div class="xiao-container">
    <el-card shadow="hover" class="chat-card">
      <template #header>
        <div class="header-content">
          <div class="header-left">
            <el-icon class="header-icon"><ChatDotRound /></el-icon>
            <span class="header-title">智能小智 - WMS智能助手</span>
            <el-tag type="success" size="small" v-if="isOnline">在线</el-tag>
            <el-tag type="info" size="small" v-else>离线</el-tag>
          </div>
          <div class="header-actions">
            <el-button size="small" @click="clearChat" :icon="Delete">清空对话</el-button>
            <el-button size="small" @click="loadHistory" :icon="Refresh" :loading="isLoadingHistory">加载历史</el-button>
          </div>
        </div>
      </template>

      <div class="chat-layout">
        <!-- 左侧：聊天区域 -->
        <div class="chat-main">
          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <div 
              v-for="message in messages" 
              :key="message.id"
              class="message-item"
              :class="{ 'user-message': message.isFromUser, 'bot-message': !message.isFromUser }"
            >
              <div class="message-avatar" v-if="!message.isFromUser">
                <el-icon><ChatDotRound /></el-icon>
              </div>
              <div class="message-content">
                <div class="message-bubble">
                  <div class="message-text" v-html="formatMessage(message.message || '')"></div>
                  <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                </div>
              </div>
              <div class="message-avatar" v-if="message.isFromUser">
                <el-icon><User /></el-icon>
              </div>
            </div>

            <!-- 输入中指示器 -->
            <div v-if="isTyping" class="typing-indicator">
              <div class="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <span class="typing-text">小智正在思考...</span>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <div class="input-container">
              <el-input
                v-model="inputMessage"
                placeholder="请输入您的问题，例如：查询苹果的库存、查看销售订单、查询客户信息等..."
                @keyup.enter="sendMessage"
                :disabled="isTyping"
                class="message-input"
                type="textarea"
                :rows="3"
                resize="none"
              />
            </div>
            
            <div class="input-actions">
              <div class="quick-actions">
                <el-button size="small" @click="sendQuickMessage('查询库存')">📦 库存查询</el-button>
                <el-button size="small" @click="sendQuickMessage('查看销售订单')">📋 销售订单</el-button>
                <el-button size="small" @click="sendQuickMessage('查看采购订单')">🛒 采购订单</el-button>
                <el-button size="small" @click="sendQuickMessage('查看入库单')">📥 入库单</el-button>
                <el-button size="small" @click="sendQuickMessage('查看出库单')">📤 出库单</el-button>
                <el-button size="small" @click="sendQuickMessage('查看仓库信息')">🏭 仓库信息</el-button>
                <el-button size="small" @click="sendQuickMessage('查看客户信息')">👥 客户信息</el-button>
                <el-button size="small" @click="sendQuickMessage('查看供应商信息')">🏢 供应商信息</el-button>
              </div>
              <el-button 
                type="primary" 
                @click="sendMessage" 
                :disabled="!inputMessage.trim() || isTyping"
                :loading="isTyping"
                size="default"
              >
                <el-icon><Promotion /></el-icon>
                发送
              </el-button>
            </div>
          </div>
        </div>

        <!-- 右侧：功能面板 -->
        <div class="sidebar">
          <el-card shadow="hover" class="sidebar-card">
            <template #header>
              <span>快速查询</span>
            </template>
            <div class="query-modules">
              <div class="module-group">
                <h4>📦 库存管理</h4>
                <el-button 
                  v-for="item in inventoryQueries" 
                  :key="item.label"
                  size="small" 
                  @click="sendQuickMessage(item.query)"
                  class="module-btn"
                >
                  {{ item.label }}
                </el-button>
              </div>
              
              <div class="module-group">
                <h4>📋 订单管理</h4>
                <el-button 
                  v-for="item in orderQueries" 
                  :key="item.label"
                  size="small" 
                  @click="sendQuickMessage(item.query)"
                  class="module-btn"
                >
                  {{ item.label }}
                </el-button>
              </div>
              
              <div class="module-group">
                <h4>📥 出入库管理</h4>
                <el-button 
                  v-for="item in warehouseQueries" 
                  :key="item.label"
                  size="small" 
                  @click="sendQuickMessage(item.query)"
                  class="module-btn"
                >
                  {{ item.label }}
                </el-button>
              </div>
              
              <div class="module-group">
                <h4>👥 客户供应商</h4>
                <el-button 
                  v-for="item in customerQueries" 
                  :key="item.label"
                  size="small" 
                  @click="sendQuickMessage(item.query)"
                  class="module-btn"
                >
                  {{ item.label }}
                </el-button>
              </div>
              
              <div class="module-group">
                <h4>📊 报表统计</h4>
                <el-button 
                  v-for="item in reportQueries" 
                  :key="item.label"
                  size="small" 
                  @click="sendQuickMessage(item.query)"
                  class="module-btn"
                >
                  {{ item.label }}
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  ChatDotRound, 
  User, 
  Promotion, 
  Delete,
  Refresh
} from '@element-plus/icons-vue';
import { useCustomerServiceApi, type CustomerServiceMessage } from '/@/api/customerService';

// API服务
const customerServiceApi = useCustomerServiceApi();

// 响应式数据
const isTyping = ref(false);
const isOnline = ref(true);
const isLoadingHistory = ref(false);
const inputMessage = ref('');
const conversationId = ref(`conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`);
const messages = ref<CustomerServiceMessage[]>([]);
const messagesContainer = ref<HTMLElement>();

// 查询模块配置
const inventoryQueries = [
  { label: '查询库存', query: '查询所有库存信息' },
  { label: '库存统计', query: '查询库存统计信息' },
  { label: '库存预警', query: '查询库存预警信息' },
  { label: '库存分布', query: '查询库存分布情况' },
];

const orderQueries = [
  { label: '销售订单', query: '查询销售订单列表' },
  { label: '采购订单', query: '查询采购订单列表' },
  { label: '退货订单', query: '查询退货订单列表' },
  { label: '订单统计', query: '查询订单统计信息' },
];

const warehouseQueries = [
  { label: '入库单', query: '查询入库单列表' },
  { label: '出库单', query: '查询出库单列表' },
  { label: '盘点单', query: '查询盘点单列表' },
  { label: '调拨单', query: '查询调拨单列表' },
];

const customerQueries = [
  { label: '客户列表', query: '查询客户信息列表' },
  { label: '供应商列表', query: '查询供应商信息列表' },
];

const reportQueries = [
  { label: '入库流水', query: '查询入库流水报表' },
  { label: '出库流水', query: '查询出库流水报表' },
  { label: '库存分布', query: '查询库存分布报表' },
  { label: '仓库汇总', query: '查询仓库汇总报表' },
];

// 格式化消息内容
const formatMessage = (text: string) => {
  if (!text) return '';
  // 简单的换行处理
  return text.replace(/\n/g, '<br>');
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value) return;

  const userMessage: CustomerServiceMessage = {
    id: Date.now(),
    userId: 1,
    userName: '用户',
    message: inputMessage.value.trim(),
    messageType: 'text',
    timestamp: new Date().toISOString(),
    isFromUser: true,
    conversationId: conversationId.value
  };

  messages.value.push(userMessage);
  const currentMessage = inputMessage.value;
  inputMessage.value = '';
  isTyping.value = true;

  scrollToBottom();

  try {
    const apiResponse = await customerServiceApi.sendMessage({
      message: currentMessage,
      conversationId: conversationId.value,
      userId: 1,
      userName: '用户'
    });

    // 处理API响应数据
    const response = apiResponse.data?.result || apiResponse.data || apiResponse;
    
    const agentResponse: CustomerServiceMessage = {
      id: Date.now() + 1,
      userId: 0,
      userName: '小智',
      message: response.message || '抱歉，我暂时无法回复您的消息。',
      messageType: 'text',
      timestamp: new Date().toISOString(),
      isFromUser: false,
      conversationId: conversationId.value,
      actions: response.actions
    };

    messages.value.push(agentResponse);
    scrollToBottom();
  } catch (error: any) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败，请稍后重试');
    
    const errorResponse: CustomerServiceMessage = {
      id: Date.now() + 1,
      userId: 0,
      userName: '小智',
      message: '抱歉，服务暂时不可用，请稍后重试。',
      messageType: 'text',
      timestamp: new Date().toISOString(),
      isFromUser: false,
      conversationId: conversationId.value
    };
    
    messages.value.push(errorResponse);
    scrollToBottom();
  } finally {
    isTyping.value = false;
  }
};

// 发送快捷消息
const sendQuickMessage = (message: string) => {
  inputMessage.value = message;
  sendMessage();
};

// 清空对话
const clearChat = () => {
  messages.value = [];
  conversationId.value = `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  ElMessage.success('对话已清空');
};

// 加载历史记录
const loadHistory = async () => {
  if (!conversationId.value) return;
  
  isLoadingHistory.value = true;
  try {
    const response = await customerServiceApi.getChatHistory(conversationId.value);
    const history = response.data?.result || response.data || [];
    
    if (Array.isArray(history) && history.length > 0) {
      messages.value = history.map((item: any) => ({
        id: item.id || Date.now() + Math.random(),
        userId: item.userId || 0,
        userName: item.userName || (item.isFromUser ? '用户' : '小智'),
        message: item.message || '',
        messageType: item.messageType || 'text',
        timestamp: item.timestamp || new Date().toISOString(),
        isFromUser: item.isFromUser !== undefined ? item.isFromUser : true,
        conversationId: item.conversationId || conversationId.value
      }));
      scrollToBottom();
      ElMessage.success(`已加载 ${history.length} 条历史记录`);
    } else {
      ElMessage.info('暂无历史记录');
    }
  } catch (error: any) {
    console.error('加载历史记录失败:', error);
    ElMessage.error('加载历史记录失败');
  } finally {
    isLoadingHistory.value = false;
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 初始化
onMounted(() => {
  // 发送欢迎消息
  const welcomeMessage: CustomerServiceMessage = {
    id: Date.now(),
    userId: 0,
    userName: '小智',
    message: '你好！我是智能小智，你的WMS智能助手。\n\n我可以帮你查询以下模块的信息：\n📦 库存查询：如"查询苹果的库存"、"XX商品还有多少"\n📋 订单查询：如"查看销售订单"、"查询采购订单PO001"\n📥 出入库查询：如"查看入库单"、"查询出库单"\n👥 客户供应商：如"查看客户信息"、"查询供应商列表"\n🏭 仓库信息：如"查看仓库信息"\n\n你可以直接提问，我会自动识别并查询相关数据，然后给你智能回答！😊',
    messageType: 'text',
    timestamp: new Date().toISOString(),
    isFromUser: false,
    conversationId: conversationId.value
  };
  messages.value.push(welcomeMessage);
});
</script>

<style scoped lang="scss">
.xiao-container {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;

  .chat-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 0;
    }
  }

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;

      .header-icon {
        font-size: 24px;
        color: #409eff;
      }

      .header-title {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .chat-layout {
    display: flex;
    flex: 1;
    overflow: hidden;
    gap: 20px;
    padding: 20px;

    .chat-main {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      background: #fff;
    }

    .sidebar {
      width: 300px;
      flex-shrink: 0;
      overflow-y: auto;
    }
  }

  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f5f7fa;

    .message-item {
      display: flex;
      margin-bottom: 20px;
      align-items: flex-start;
      gap: 12px;

      &.user-message {
        flex-direction: row-reverse;

        .message-bubble {
          background: #409eff;
          color: #fff;
          border-radius: 12px 12px 4px 12px;
        }
      }

      &.bot-message {
        .message-bubble {
          background: #fff;
          color: #303133;
          border-radius: 12px 12px 12px 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }

      .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #e4e7ed;
        color: #606266;
        flex-shrink: 0;

        .el-icon {
          font-size: 20px;
        }
      }

      .message-content {
        max-width: 70%;
        min-width: 100px;

        .message-bubble {
          padding: 12px 16px;
          word-wrap: break-word;
          word-break: break-all;

          .message-text {
            line-height: 1.6;
            font-size: 14px;
          }

          .message-time {
            font-size: 12px;
            opacity: 0.7;
            margin-top: 6px;
          }
        }
      }
    }

    .typing-indicator {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 12px 16px;
      background: #fff;
      border-radius: 12px;
      margin-bottom: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .typing-dots {
        display: flex;
        gap: 4px;

        span {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: #409eff;
          animation: typing 1.4s infinite;

          &:nth-child(2) {
            animation-delay: 0.2s;
          }

          &:nth-child(3) {
            animation-delay: 0.4s;
          }
        }
      }

      .typing-text {
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .input-area {
    border-top: 1px solid #e4e7ed;
    padding: 16px;
    background: #fff;

    .input-container {
      margin-bottom: 12px;
    }

    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12px;

      .quick-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        flex: 1;
      }
    }
  }

  .sidebar-card {
    margin-bottom: 20px;

    .query-modules {
      .module-group {
        margin-bottom: 20px;

        h4 {
          margin: 0 0 12px 0;
          font-size: 14px;
          font-weight: 600;
          color: #303133;
        }

        .module-btn {
          width: 100%;
          margin-bottom: 8px;
          justify-content: flex-start;
        }
      }
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}
</style>

